package com.rainng.coursesystem.controller;

import com.rainng.coursesystem.dto.FollowedUserDTO;
import com.rainng.coursesystem.model.FavouriteItem;
import com.rainng.coursesystem.service.FavouriteService;
import com.rainng.coursesystem.service.FollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/follows") // 新的 Controller 路径
public class FollowController {

    @Autowired
    private FollowService followService;
    private FavouriteService favouriteService;


    @PostMapping("/follow")
    public ResponseEntity<String> followUser(@RequestParam String followerNumber, @RequestParam String followedNumber) {
        try {
            followService.follow(followerNumber, followedNumber);
            return ResponseEntity.ok("关注成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage()); // 返回更具体的错误信息
        }
    }

    @PostMapping("/unfollow")
    public ResponseEntity<String> unfollowUser(@RequestParam String followerNumber, @RequestParam String followedNumber) {
        try {
            followService.unfollow(followerNumber, followedNumber);
            return ResponseEntity.ok("取消关注成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/listFollowing")
    public ResponseEntity<List<FollowedUserDTO>> listFollowing(@RequestParam String followerNumber) {
        List<FollowedUserDTO> following = followService.listFollowing(followerNumber);
        return following.isEmpty() ? ResponseEntity.noContent().build() : ResponseEntity.ok(following);
    }

    // 查看被关注用户的收藏夹
    @GetMapping("/followedFavourites")
    public ResponseEntity<List<FavouriteItem>> listFollowedFavourites(@RequestParam String followerNumber) {
        List<FavouriteItem> favourites = followService.listFollowedFavourites(followerNumber);

        // 过滤掉未公开的收藏夹
        List<FavouriteItem> publicFavourites = favourites.stream()
                .filter(FavouriteItem::isPublic)
                .collect(Collectors.toList());

        if (publicFavourites.isEmpty()) {
            return ResponseEntity.noContent().build(); // 返回 204 No Content
        } else {
            return ResponseEntity.ok(publicFavourites);
        }
    }
}
